<?php

namespace Xin\Robot;

class FeiShuRobot extends AbstractRobot
{

	/**
	 * 飞书机器人的 API 地址
	 * @var string
	 */
	protected $baseUrl = 'https://open.feishu.cn/open-apis/bot/v2/';

	/**
	 * FeiShuRobot Constructor
	 * @param array{
	 *     key:string,
	 *     secret:string,
	 * } $config
	 */
	public function __construct(array $config)
	{
		parent::__construct($config);
	}

	/**
	 * 构建请求的URL
	 * @return string
	 */
	protected function buildApiUrl()
	{
		return "hook/{$this->config['key']}";
	}


	/**
	 * 生成签名数据
	 * @param int $timestamp
	 * @return string
	 */
	protected function sign($timestamp)
	{
		// 安全密钥
		$secretKey = $this->config['secret'];

		// 准备签名字符串
		$signStr = ($timestamp) . "\n" . $secretKey;

		// 使用 HmacSHA256 算法计算签名
		return base64_encode(hash_hmac('sha256', '', $signStr, true));
	}

	/**
	 * 构造新的消息体
	 * @param array $message
	 * @return array
	 */
	protected function newMessage(array $message)
	{
		if (isset($this->config['secret']) && !empty($this->config['secret'])) {
			$timestamp = now()->getTimestamp();
			$message['timestamp'] = $timestamp;
			$message['sign'] = $this->sign($timestamp);
		}

		return $message;
	}

	/**
	 * @inheritDoc
	 */
	public function sendMessage(array $message, array $mentionedList = null)
	{
		if ($mentionedList) {
			if ($message['msg_type'] === 'text') {
				$atArr = array_map(function ($at) {
					$at = ltrim($at, "@");
					return "<at user_id=\"{$at}\"></at>";
				}, $mentionedList);
				$atStr = implode("", $atArr);
				$message['content']['text'] .= "\n" . $atStr;
			} elseif ($message['msg_type'] === 'interactive') {
				$atArr = array_map(function ($at) {
					$at = ltrim($at, "@");
					return "<at id={$at}></at>";
				}, $mentionedList);
				$atStr = implode("", $atArr);
				$message['card']['elements'][] = [
					"tag" => "div",
					"text" => [
						"content" => $atStr,
						"tag" => "lark_md",
					],
				];
			}
		}

		$response = $this->client()->post($this->buildApiUrl(), $this->newMessage($message));

		return $response->ok() && $response->data('code') === 0;
	}

	/**
	 * @inheritDoc
	 */
	public function sendTextMessage(string $content, array $mentionedList = null, array $attributes = [])
	{
		return $this->sendMessage(array_merge($attributes, [
			'msg_type' => 'text',
			'content' => [
				'text' => $content,
			],
		]), $mentionedList);
	}

	/**
	 * @inheritDoc
	 */
	public function sendMarkdownMessage($content, array $mentionedList = null, array $attributes = [])
	{
		return $this->sendMessage(array_merge($attributes, [
			'msg_type' => 'interactive',
			'card' => [
				'elements' => [
					[
						"tag" => "div",
						"text" => [
							"content" => $content,
							"tag" => "lark_md",
						],
					],
				],
			],
		]), $mentionedList);
	}

	/**
	 * @inheritDoc
	 */
	public function sendFeedCardMessage($articles, array $mentionedList = null, array $attributes = [])
	{
		$elements = [];
		foreach ($articles as $article) {
			if (isset($article['picurl'])) {
				$elements[] = [
					'tag' => 'div',
					'text' => [
						'tag' => 'lark_md',
						'content' => "<img src='{$article['picurl']}'/>",
					],
				];
			}

			if (isset($article['title'])) {
				$elements[] = [
					'tag' => 'div',
					'text' => [
						'tag' => 'lark_md',
						'content' => $article['title'],
					],
				];
			}
			if (isset($article['url'])) {
				$elements[] = [
					'actions' => [
						[
							"tag" => "button",
							"text" => [
								"content" => "更多",
								"tag" => "lark_md",
							],
							"url" => $article['url'],
							"type" => "default",
						],
					],
					"tag" => "action",
				];
			}
		}

		return $this->sendMessage(array_merge($attributes, [
			'msg_type' => 'interactive',
			'card' => [
				//                'header' => Arr::get($attributes, 'header'),
				'elements' => $elements,
			],
		]), $mentionedList);
	}

}
